package it.ebruni.caroid;

import it.ebruni.caroid.R.id;

import java.util.ListIterator;

import android.R.layout;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.database.Cursor;

public class Mp3player extends FragmentActivity implements MultimediaPlayerListener, SeekBar.OnSeekBarChangeListener, 
	LoaderManager.LoaderCallbacks<Cursor> {
	
	// Internal Objects
	private MultimediaPlayer mp = new MultimediaPlayer();
	private SongsManager songManager = new SongsManager();
	private Handler tmrUpdateProgressBar = new Handler();
	private ListIterator<FileSong> songsIterator;
	private SimpleCursorAdapter adpListview;
	private Cursor curCurrentSong;
	private int intPosition;
	
	// GUI Objects
	private SeekBar pbSong;
	private ImageButton btnPlayPause;
	private TextView txtHeader;
	private ListView lvSongs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mp3player);
		
		// Get GUI Objects
		pbSong = (SeekBar) findViewById(R.id.pbSong);
		btnPlayPause = (ImageButton) findViewById(R.id.btnPlayPause);
		txtHeader=(TextView) findViewById(id.txtHeader);
		lvSongs =(ListView) findViewById(id.lvSongs);
		
		// config Objects
		mp.setMultimediaPlayerListener(this);
		pbSong.setOnSeekBarChangeListener(this);
		
		String[] fromColumns = { Audio.Media.TITLE, Audio.Media.ARTIST};
		int[] toViews = {R.id.txtSongTitle, R.id.txtSongAuthor};
		adpListview=new SimpleCursorAdapter(this,R.layout.song_info,null,fromColumns,toViews);
		lvSongs.setAdapter(adpListview);
		
		lvSongs.setOnItemClickListener(lvSongs_onItemClick);
		this.getSupportLoaderManager().initLoader(0, null, this);

	}
	
	 private OnItemClickListener lvSongs_onItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> listView, View arg1, int position,
				long id) {
			intPosition = position;
			curCurrentSong = (Cursor) listView.getItemAtPosition(intPosition);	
			FileSong fSong = new FileSong(curCurrentSong);
			Log.d("Mp3player" ,"lvSongs_onItemClick() called - start playing song " + fSong.getPath());
			mp.playSong(fSong);
		}
	}; 
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.mp3player, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		//case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
		//	NavUtils.navigateUpFromSameTask(this);
		//	return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void btnPlayPause_onClick(View item) {
		if(mp.isPlaying()){
			mp.pause();
		} else {
			mp.start();
		}
	}

	public void btnNext_onClick(View item) {
		playNext();
	}

	private void playNext() {
		intPosition++;
		if (intPosition > adpListview.getCount()-1) {
			intPosition=0;
		}		
		curCurrentSong = (Cursor) adpListview.getItem(intPosition);	
		FileSong fSong = new FileSong(curCurrentSong);
		Log.d("Mp3player" ,"playNext called - start playing song " + fSong.getPath());
		mp.playSong(fSong);
	}

	
	private Runnable thrUpdateProgressBar = new Runnable() {		
		@Override
		public void run() {
			long currentPos = mp.getCurrentPosition();
			pbSong.setProgress((int) currentPos/1000);
			tmrUpdateProgressBar.postDelayed(this, 500);
			
		}
	};
	
	@Override
	public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		tmrUpdateProgressBar.removeCallbacks(thrUpdateProgressBar);
	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		mp.pause();
		mp.seekTo(arg0.getProgress()*1000);
		mp.start();
	}

	@Override
	public void onMediaStart(MultimediaPlayer mp) {
		btnPlayPause.setImageResource(R.drawable.btn_pause);
		FileSong cS = mp.getCurrentSong();
		txtHeader.setText(cS.getArtist() + " - " +  cS.getTitle());
		tmrUpdateProgressBar.removeCallbacks(thrUpdateProgressBar);
		pbSong.setMax((int) mp.getDuration()/1000);
		tmrUpdateProgressBar.postDelayed(thrUpdateProgressBar, 500);
	}

	@Override
	public void onMediaPause(MultimediaPlayer mp) {
		btnPlayPause.setImageResource(R.drawable.btn_play);
		tmrUpdateProgressBar.removeCallbacks(thrUpdateProgressBar);
	}

	@Override
	public void onMediaComplete(MultimediaPlayer mp) {
		playNext();
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

		String[] projection = {
		        Audio.Media._ID,
		        Audio.Media.ARTIST,
		        Audio.Media.TITLE,
		        Audio.Media.DATA,
		        Audio.Media.DISPLAY_NAME,
		        Audio.Media.DURATION
		};
		
		return new CursorLoader(this,Audio.Media.EXTERNAL_CONTENT_URI,
		        projection,
		        selection,
		        null,
		        null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		// TODO Auto-generated method stub
		adpListview.changeCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub
		adpListview.changeCursor(null);
	}
}
